# -*- coding: utf-8 -*-
from django.shortcuts import render,redirect
from django.http import HttpResponsePermanentRedirect,HttpResponse

# Create your views here.
from django.views.generic import View  #这是django给我们的视图类
from .models import  Upload
import random
import string
import datetime
import json

class HomeView(View):   #定义了HomeView这个类
    def get(self,request):
        return render(request,"base.html")
    def post(self,request):
        if request.FILES:
            #有文件就向下执行，没有文件的情况，前端已经处理好
            file = request.FILES.get('file')
            name = file.name
            size = file.size
            PCIP = str(request.META.get("REMOTE_ADDR"))
            print 'PCIP=%s'%PCIP

            #将文件写到static/files
            with open('static/file/'+name,'wb') as f:
                f.write(file.read())
            #生成随机八位的code
            code = ''.join(random.sample(string.digits,8))
###################
##这里保存错误是为什么
#######################
            path = 'static/file/' + name
            print'path=%s'%path
            u = Upload(
                path = path,
                name = name,
                Filesize = size,
                code = code,

                #获取上传文件的用户IP
                PCIP = PCIP,
            )
            u.save()
            print 'u.name=%s,u.path=%s,u.Filesize=%s,u.code=%s' % (u.name,u.path,u.Filesize,u.code)
            #适用HttpResponsePermanentRedirect重定向到展示文件的页面，这里的code唯一标识一个文件

            # return HttpResponse(u'hello')

            return redirect("/display/"+code)


def Dispaly(request):
    return HttpResponse('hello word')


#展示文件的视图类
class DisplayView(View):
    def get(self,request,code):
        # return HttpResponse('hello')
        u = Upload.objects.filter(code=str(code))


        if u:
            for i in u:
                i.DownloadDocount += 1
                i.save()
                # print 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'
                # print 'i.name=%s,i.path=%s,i.Filesize=%s,i.code=%s' % (i.name,i.path,i.Filesize,i.code)
        return render(request,'content.html',{'content':u})

#定义一个MyView用于完成用户管理功能
class MyView(View):
    # def get(self,request):
    #     return HttpResponse(u'hello word')
    def get(self,request):

        IP = request.META['REMOTE_ADDR']   #获取用户的IP

        u  = Upload.objects.filter(PCIP=str(IP))  #查找数据
        print 'u=%s'%u
        for i in u:
            i.DownloadDocount += 1    #访问量+1
            i.save()
        return render(request,'content.html',{'content':u})

class SearchView(View):
    def get(self,request):
        code = request.GET.get("kw")  #获取get请求中的kw的值，即搜索的内容
        print 'code=%s'% code
        u = Upload.objects.filter(name=str(code))
        print '----------------------'
        print 'u=%s'%len(u)
        data = {}
        if len(u) == 0:
            return HttpResponse(u'请重新输入')

        else:
            for i in range(len(u)):
                #'''将符合条件的数据放到data中'''
                u[i].DownloadDocount += 1
                u[i].save()
                data[i] = {}
                data[i]['download'] = u[i].DownloadDocount
                data[i]['filename'] = u[i].name
                data[i]['ip'] = str(u[i].PCIP)
                data[i]['size'] = u[i].Filesize
                data[i]['time'] = str(u[i].Datatime.strftime('%Y-%m-%d %H:%M'))

                data[i]['key'] = u[i].code
            return HttpResponse(json.dumps(data),content_type='application/json')